import cv2
import matplotlib.pyplot as plt

filename = 'img/bread.png'
opencv_logo = 'img/opencv_logo.png'


# 使用Matplotlib显示图像
def matplotlibShowImg(title, image):
    plt.title(title)
    plt.imshow(image, interpolation='bicubic')
    plt.xticks([]), plt.yticks([])  # 隐藏坐标轴刻度
    plt.show()


def moveImgArea():
    image = cv2.imread(filename, cv2.IMREAD_COLOR)
    # 选取特定区域
    matplotlibShowImg('testShow', image)
    area = image[50:450, 70:470]
    print(area.shape)
    # 将area设置到图像的另一个位置上
    image[80:480, 100:500] = area
    cv2.imshow('roi', image)
    cv2.waitKey()
    cv2.destroyAllWindows()


def bitOpreation():
    bread = cv2.imread(filename)
    opencvLogo = cv2.imread(opencv_logo)
    rows, cols, channels = opencvLogo.shape
    roi = bread[0:rows, 0:cols]
    # 创建掩码图像和它的反转图像
    img2gray = cv2.cvtColor(opencvLogo, cv2.COLOR_BGR2GRAY)
    # 用阈值化方法创建掩码，灰度值<10为黑色，反之为白色
    ret, mask = cv2.threshold(img2gray, 10, 255, cv2.THRESH_BINARY)
    mask_inv = cv2.bitwise_not(mask)
    # 在源图像上用反码抠出log（log图像设置为黑色，其余不变）
    img_bg = cv2.bitwise_and(roi, roi, mask=mask_inv)
    # 在logo上用掩码去除背景（log图像保持不变，背景变为黑色）
    img_fg = cv2.bitwise_and(opencvLogo, opencvLogo, mask=mask)
    # 将log图像叠加到源图像上，获得透明效果
    dst = cv2.add(img_bg, img_fg)
    bread[0:rows, 0:cols] = dst
    cv2.imshow('bread + opencv_logo',bread)
    cv2.waitKey(0)
    cv2.destroyAllWindows()


bitOpreation()
